<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23
 * Time: 13:53
 */

namespace app\admin\controller;


use think\Controller;
use think\Db;

class Login extends Controller
{
    public function index()
    {
        if (cookie('admin'))
        {
            $this->redirect('admin/index/index');
        } else {
            return view('login');
        }
    }

    //后台登陆
    public function doLogin()
    {
        if (request()->isPost())
        {
            $username = input('param.username');
            $password = input('param.password');
            $row      = Db::name('admin')
                ->field('id, username, password, status')
                ->where('username', $username)
                ->find();
            if (!empty($row))
            {
                $hash = get_hash_pass($password);
                if ($row['password'] == $hash)
                {
                    if ($row['status'])
                    {
                        cookie('admin', $row['id']);
                        $this->success('登录成功！', 'index', 3);
                    } else {
                        $this->error('该账号已被禁用，无法登陆！', 'index', 3);
                    }
                } else {
                    $this->error('密码输入错误！', 'index', 3);
                }
            } else {
                $this->error('您输入的帐号不存在，请重新输入！', 'index', 3);
            }
        }
    }

    public function loginOut()
    {
        cookie('admin', null);
        $this->success('退出成功！', 'index', 3);
    }

    public function changePass()
    {
        if (request()->isPost())
        {
            $oldPass      = input('param.old_pass');
            $newPass      = input('param.new_pass');
            $confirm_pass = input('param.confirm_pass');
            $adminInfo    = Db::name('admin')
                ->field('id, username, password')
                ->where('id', cookie('admin'))
                ->find();
            $hash         = get_hash_pass($oldPass);
            if ($hash != $adminInfo['password'])
            {
                $this->error('原密码不正确，请重新输入！');
            }
            if ($newPass != $confirm_pass)
            {
                $this->error('两次输入的密码不一致，请重新输入！');
            }
            $pass         = get_hash_pass($newPass);
            $res          = Db::name('admin')->where('id', cookie('admin'))->update(['password'=>$pass]);
            $res          ? $this->success('修改成功！', url('admin/index/index')) : $this->error('修改成功！', url('admin/index/index'));
        }
    }
}